package com.huadao.pda.material;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;

import com.huadao.pda.R;
import com.huadao.pda.base.BaseListDF;
import com.huadao.pda.base.BasePresenter;
import com.huadao.pda.base.OnScanResult;
import com.huadao.pda.common.ToastUtil;
import com.huadao.pda.common.adapter.CommonRecycleAdapter;
import com.huadao.pda.common.adapter.CommonViewHolder;
import com.huadao.pda.common.adapter.FooterHolder;
import com.huadao.pda.common.adapter.HeaderHolder;
import com.huadao.pda.common.adapter.onItemCommonClickListener;
import com.huadao.pda.common.dialog.DialogFragmentHelper;
import com.huadao.pda.data.bean.Dispensing;
import com.huadao.pda.data.bean.Project;
import com.huadao.pda.main.scanView.ScanDF;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class MaterialListDF extends BaseListDF implements IMaterialContract.IMaterialView,OnScanResult, MaterialDetailDF.OnGetMaterial {

    private MaterialPresenter materialPresenter;
    private List<Dispensing> materialList;

    @BindView(R.id.spinner_day)
    Spinner spinnerDay;

    private Project project;
    private Integer day;

    public static MaterialListDF newInstance(Project project) {
        Bundle args = new Bundle();
        args.putSerializable("project",project);


        MaterialListDF fragment = new MaterialListDF();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public int getRecycleViewId() {
        return R.id.recycleView;
    }

    @Override
    public int getSwipeRefreshLayoutId() {
        return R.id.srl;
    }

    @Override
    protected void init() {
        setTitle("物料列表");
        materialPresenter=new MaterialPresenter(this);

        Bundle bundle=getArguments();
        if(bundle!=null){
            project= (Project) bundle.get("project");
        }

        materialList=new ArrayList<>();
        setBackVisibility(View.VISIBLE);

        List<String> dayList=new ArrayList<>();
        dayList.add("全部");

        if(getProjectStartTime()!=null) {
            Calendar now = Calendar.getInstance();
            now.setTime(new Date());
            Calendar projectStartTime = Calendar.getInstance();
            projectStartTime.setTime(getProjectStartTime());

            int daysBetween;
            int projectStartYear = projectStartTime.get(Calendar.YEAR);
            int nowYear = now.get(Calendar.YEAR);
            //项目如果在一年内
            if (projectStartYear == nowYear) {
                daysBetween = now.get(Calendar.DAY_OF_YEAR) - projectStartTime.get(Calendar.DAY_OF_YEAR) + 1;
            } else {
                daysBetween = now.get(Calendar.DAY_OF_YEAR) + projectStartTime.getActualMaximum(Calendar.DAY_OF_YEAR) - projectStartTime.get(Calendar.DAY_OF_YEAR) + 1;
            }

            for (int i = 0; i < daysBetween; i++) {
                dayList.add("DAY" + (i + 1));
            }
        }
        //适配器
        ArrayAdapter arr_adapter= new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item, dayList);
        //设置样式
        arr_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        //加载适配器
        spinnerDay.setAdapter(arr_adapter);
        spinnerDay.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                if(i==0){
                    materialPresenter.getMaterialList();
                }else {
                    materialPresenter.getMaterialListByDay(i);
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });
    }

    @Override
    protected RecyclerView.ItemDecoration setItemDecoration() {
        return new DividerItemDecoration(getActivity(),DividerItemDecoration.VERTICAL);
    }

    @Override
    protected CommonRecycleAdapter setAdapter() {
        return new MaterialAdapter(getActivity(),materialList,R.layout.item_material);
    }

    @Override
    public RecyclerView.LayoutManager setLayoutManage() {
        return new LinearLayoutManager(getActivity());
    }

    @Override
    protected void loadData() {
        materialPresenter.getMaterialList();
    }

    @OnClick({R.id.btn_cancel, R.id.btn_finish_get,R.id.btn_scan})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_cancel:
                this.dismiss();
                break;
            case R.id.btn_finish_get:
                materialPresenter.finishGet();
                break;
            case R.id.btn_scan:
                ScanDF scanDF=new ScanDF();
//                scanDF.setOnScanResult(this);
                scanDF.show(getFragmentManager(),null);
                break;
        }
    }

    @Override
    public void onScanResult(String barcode) {
//        final Dispensing dispensing=GsonUtil.getInstance().fromJson(barcode,Dispensing.class);
//        if(dispensing==null){
//            return;
//        }

        final Dispensing dispensing=getDispensingByBarCode(barcode);
        if(dispensing==null){
            showToast("条形码："+barcode+" 物料不在列表中");
            return;
        }
        if(!dispensing.getProjectId().equals(project.getProjectId())){
            DialogFragmentHelper.showMessageDialog(getActivity(),"","此物料非本项目的物料，请确认物料条形码并重新扫码！");
            return;
        }

        MaterialDetailDF detailDF=MaterialDetailDF.newInstance(dispensing,true);
        detailDF.setOnGetMaterial(this);
        detailDF.show(getFragmentManager(),null);

//        DialogFragmentHelper.showMaterialDialog(getActivity(), dispensing, true,new IDialogResultListener<Integer>() {
//            @Override
//            public void onDataResult(Integer result) {
//                if(result==DialogInterface.BUTTON_POSITIVE){
//                    materialPresenter.consumeMaterial(dispensing);
//                }
//            }
//        });

//        RockToast.showToastSafe(barcode);
//        stopScan();
    }



    private Dispensing getDispensingByBarCode(String barCode){
        if(materialList==null||TextUtils.isEmpty(barCode)){
            return null;
        }
        for(Dispensing dis:materialList){
            if(barCode.equals(dis.getBarCode())){
                return dis;
            }
        }
        return null;
    }

    @Override
    public void onGetMaterialList(List<Dispensing> materialList) {
        if(materialList==null||materialList.size()==0){
            showToast("没有数据");
        }
        setSwipeRefresh(false);
        this.materialList.clear();
        this.materialList.addAll(materialList);
        notifyDataSetChanged();
    }

    @Override
    public void onConsumeMaterial(Dispensing dispensing, boolean isSucc) {
        if(isSucc) {
            showToast("领取成功");
            int index = materialList.indexOf(dispensing);
            if (index != -1) {
                materialList.get(index).setUse(isSucc);
                notifyDataSetChanged();
            }
        }
    }

    @Override
    public void onFinishGet() {
        ToastUtil.showTextToast(getActivity(),"领取完成啦");
        this.dismiss();
    }

    @Override
    public String getProjectId() {
        if(project==null){
            return null;
        }
        return project.getProjectId();
    }

    @Override
    public Date getProjectStartTime() {
        if(project==null){
            return null;
        }
        return project.getStartTime();
    }

    @Override
    protected BasePresenter getPresenter() {
        return materialPresenter;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_material;
    }

    @Override
    public void onGetMaterial(Dispensing dispensing) {
        materialPresenter.consumeMaterial(dispensing);
    }

    class MaterialAdapter extends CommonRecycleAdapter<Dispensing>{

        private onItemCommonClickListener onItemCommonClickListener=new onItemCommonClickListener() {
            @Override
            public void onItemClickListener(int position) {
                Dispensing material=materialList.get(position);
                MaterialDetailDF detailDF=MaterialDetailDF.newInstance(material,false);
//                detailDF.setOnGetMaterial(MaterialListDF.this);
                detailDF.show(getFragmentManager(),null);
//                DialogFragmentHelper.showMaterialDialog(getActivity(), material, false,new IDialogResultListener<Integer>() {
//                    @Override
//                    public void onDataResult(Integer result) {
//
//                    }
//                });
            }

            @Override
            public void onItemLongClickListener(int position) {

            }
        };

        public MaterialAdapter(Context context, List<Dispensing> dataList, int layoutId) {
            super(context, dataList, layoutId);
        }

        @Override
        protected void bindData(CommonViewHolder holder, Dispensing data,int position) {
            holder.setText(R.id.tv_NO,String.valueOf(position+1));
            holder.setText(R.id.tv_materialName,data.getName());
            holder.setText(R.id.tv_materialNumber,data.getBarCode());
            if(data.isUse()){
                holder.setText(R.id.tv_status,"已领取");
                holder.setTextColor(R.id.tv_status,getResources().getColor(R.color.green));
            }else {
                holder.setText(R.id.tv_status,"未领取");
                holder.setTextColor(R.id.tv_status,getResources().getColor(R.color.red));
            }
            holder.setCommonClickListener(onItemCommonClickListener);
        }

        @Override
        protected void bindFooterData(FooterHolder holder) {

        }

        @Override
        protected void bindHeaderData(HeaderHolder holder) {

        }
    }
}
